package com.hr.system.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateUtil {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 计算本周工作日范围
     */
    public static Date[] calWorkDate() throws ParseException {
        Date[] result = new Date[2];

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 获取本周的第一个工作日（假设周一至周五为工作日）
        LocalDate firstWorkDayOfWeek = currentDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));

        // 获取本周的最后一个工作日
        LocalDate lastWorkDayOfWeek = currentDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));
        result[0] = DATE_FORMAT.parse(String.valueOf(firstWorkDayOfWeek));
        result[1] = DATE_FORMAT.parse(String.valueOf(lastWorkDayOfWeek));
        return result;
    }

    /**
     * 计算日期相减
     */
    public static Date calSubDate(Date date, int days) throws ParseException {
        LocalDate curDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        // 减去7天
        return DATE_FORMAT.parse(curDate.minusDays(days).toString());
    }

    /**
     * 获取当前日期属于当月的第几周
     */
    public static int calWhatWeek(Date curDate) {
        LocalDate localDate = curDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        // 获取当前地区的周开始日
        WeekFields weekFields = WeekFields.of(Locale.getDefault());

        return localDate.get(weekFields.weekOfMonth());
    }

    /**
     * 获取日期的月份
     * @return
     */
    public static int getMonth(Date curDate) {
        LocalDate localDate = curDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 获取月份
        return localDate.getMonthValue();
    }

    public static Date[] calMonthDate() throws ParseException {
        Date[] result = new Date[2];
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取本月的第一个工作日
        LocalDate firstDay = currentDate.with(TemporalAdjusters.firstDayOfMonth());
        //获取本月的最后一个工作日
        LocalDate lastDay  = currentDate.with(TemporalAdjusters.lastDayOfMonth());
//        result[0] = DATE_FORMAT.parse(calendar.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString());
        result[0] = DATE_FORMAT.parse(firstDay.toString());
        result[1] = DATE_FORMAT.parse(lastDay.toString());
        return result;
    }
}
